package com.dpp.controller.user;

import com.dpp.config.WxInformation;
import com.dpp.constant.JwtClaimsConstant;
import com.dpp.entity.Users;
import com.dpp.properties.JwtProperties;

import com.dpp.service.UserService;
import com.dpp.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@RestController
@Slf4j
@RequestMapping("/user/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录
     *
     * @param code
     * @return
     */
    @Transactional
    @GetMapping("/login")
    public void login(String code, HttpServletResponse resp) throws IOException {
        //用户登录获取openid
        Users user = userService.login(code);
        if (user != null) {
            HashMap<String, Object> claimsMap = new HashMap<>();
            claimsMap.put(JwtClaimsConstant.OPEN_ID, user.getOpenid());
            //创建jwt令牌
            String Newtoken = JwtUtil.createJWT(
                    jwtProperties.getUserSecretKey(),
                    jwtProperties.getUserTtl(),
                    claimsMap);
            //将jwt令牌给前端，内容是用户的openid
            String url = jwtProperties.getUrl().concat("/home.html?token=" + Newtoken);
            resp.sendRedirect(url);
        }
    }

}
